<?php
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;

require 'vendor/autoload.php';

class EmailValidator {
    private $mail;
    private $verificationCode;
    private $recipientEmail;
    private $subject = "邮箱验证";
    private $fromEmail;
    private $fromName;

    // 构造函数
    public function __construct($fromEmail, $fromName) {
        $this->fromEmail = $fromEmail;
        $this->fromName = $fromName;
        $this->mail = new PHPMailer(true);
        $this->configureSMTP();
    }

    // 配置SMTP服务器
    private function configureSMTP() {
        $this->mail->SMTPDebug = 0; // 关闭调试输出
        $this->mail->isSMTP();
        $this->mail->Host = 'smtp.example.com'; // 替换为你的SMTP服务器地址
        $this->mail->SMTPAuth = true;
        $this->mail->Username = $this->fromEmail; // 替换为你的邮箱地址
        $this->mail->Password = 'your-email-password'; // 替换为你的邮箱密码
        $this->mail->SMTPSecure = 'tls'; // 或 'ssl'
        $this->mail->Port = 587; // 或 465
    }

    // 生成验证码
    private function generateVerificationCode() {
        return rand(1000, 9999); // 生成4位随机验证码
    }

    // 发送验证邮件
    public function sendVerificationEmail($recipientEmail) {
        $this->recipientEmail = $recipientEmail;
        $this->verificationCode = $this->generateVerificationCode();

        try {
            $this->mail->setFrom($this->fromEmail, $this->fromName);
            $this->mail->addAddress($this->recipientEmail);
            $this->mail->isHTML(true);
            $this->mail->Subject = $this->subject;
            $this->mail->Body = "您的验证码是：<b>{$this->verificationCode}</b>";

            if ($this->mail->send()) {
                return true;
            } else {
                throw new Exception("邮件发送失败: " . $this->mail->ErrorInfo);
            }
        } catch (Exception $e) {
            return false;
        }
    }

    // 验证用户输入的验证码
    public function verifyCode($userCode) {
        return $userCode === $this->verificationCode;
    }

    // 获取验证码（仅用于测试，实际开发中应存储在数据库或会话中）
    public function getVerificationCode() {
        return $this->verificationCode;
    }

    // 获取收件人邮箱
    public function getRecipientEmail() {
        return $this->recipientEmail;
    }
}